package com.ruoyi.common.utils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.time.DateFormatUtils;

/**
 * 时间工具类
 *
 * @author ruoyi
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};


    private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
            .withZone(ZoneId.systemDefault());

    private static DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static String getDate1() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static String getDate2() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算相差天数
     */
    public static int differentDaysByMillisecond(Date date1, Date date2) {
        return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
    }

    /**
     * 计算时间差
     *
     * @param endDate   最后时间
     * @param startTime 开始时间
     * @return 时间差（天/小时/分钟）
     */
    public static String timeDistance(Date endDate, Date startTime) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - startTime.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor) {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor) {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    public static List<String> getNextNDays(int n) {
        List<String> dateList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); // 日期格式

        // 循环输出从今天开始的n天日期
        for (int i = 0; i < n; i++) {
            dateList.add(dateFormat.format(calendar.getTime())); // 将日期格式化为字符串并添加到列表中
            calendar.add(Calendar.DAY_OF_MONTH, 1); // 增加一天
        }

        return dateList;
    }

    /**
     * 取时间区间
     *
     * @param startDate
     * @param endDate
     * @return
     */
    public static List<String> getDatesInRange(String startDate, String endDate) {
        List<String> dateList = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        LocalDate start = LocalDate.parse(startDate, formatter);
        LocalDate end = LocalDate.parse(endDate, formatter);

        while (!start.isAfter(end)) {
            dateList.add(start.format(formatter));
            start = start.plusDays(1);
        }

        return dateList;
    }

    public static List<String> getDates() {
        List<String> dates = new ArrayList<>();
        LocalDate today = LocalDate.now();
        LocalDate tenDaysLater = today.plusDays(10);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        dates.add(today.format(formatter));
        dates.add(tenDaysLater.format(formatter));
        return dates;
    }

    /**
     * 是不是在同一天
     *
     * @param time1
     * @param time2
     * @return
     */
    public static boolean isOnTheSameDay(String time1, String time2) {

        try {
            time1 = time1.substring(0, 10);
            time2 = time2.substring(0, 10);
            if (time1.equals(time2)) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        return true;
    }

    /**
     * 往后多少天
     *
     * @param days
     * @return
     */
    public static String getFutureDateAsString(int days) {
        LocalDate today = LocalDate.now();
        LocalDate futureDate = today.plusDays(days);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        return futureDate.format(formatter);
    }

    public static String getTimestampByDay(String day) {
        LocalDate localDate = LocalDate.parse(day);
        Instant instant = localDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
        long timestamp = instant.toEpochMilli();
        return timestamp + "";
    }

    /**
     * 加N个小时
     *
     * @param overdue
     * @return
     */
    public static String getOverdueTime(int overdue) {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();

        // 加上一个小时
        LocalDateTime twoHoursLater = now.plusHours(overdue);

        // 格式化输出
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedTime = twoHoursLater.format(formatter);

        return formattedTime;
    }

    /**
     * 取间隔分钟,返回long
     *
     * @param timeA
     * @param timeB
     * @return
     */
    public static long calculateMinutesDifference(String timeA, String timeB) {
        // Define the date-time format
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // Parse the strings into LocalDateTime objects
        LocalDateTime dateTimeA = LocalDateTime.parse(timeA, formatter);
        LocalDateTime dateTimeB = LocalDateTime.parse(timeB, formatter);

        // Calculate the difference in minutes
        Duration duration = Duration.between(dateTimeA, dateTimeB);
        return duration.toMinutes();
    }

    /**
     * 判断某日期是否存在某个星期
     *
     * @param day
     * @param weekDays
     * @return
     */
    public static boolean isDateInWeekdays(String day, List<Integer> weekDays) {
        LocalDate date = LocalDate.parse(day);
        DayOfWeek dayOfWeek = date.getDayOfWeek();
        int dayValue = dayOfWeek.getValue();
        return weekDays.contains(dayValue);
    }

    public static String getYesterday() {
        // 获取昨天的日期
        LocalDate yesterday = LocalDate.now().minusDays(1);

        // 创建一个格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // 格式化昨天的日期为字符串
        String formattedYesterday = yesterday.format(formatter);

        return formattedYesterday;
    }

    public static String getYesterday(String inputDate) {
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // 将输入的日期字符串解析为 LocalDate 对象
        LocalDate date = LocalDate.parse(inputDate, formatter);

        // 获取前一天的日期
        LocalDate yesterday = date.minusDays(1);

        // 格式化昨天的日期为字符串
        String formattedYesterday = yesterday.format(formatter);

        return formattedYesterday;
    }

    /**
     * 专门用于计算支付日期的方法
     *
     * @param initDate 初始日期
     * @param type     类型
     * @return
     */
    public static LocalDate getPaymentDate(LocalDate initDate, String type) {
        LocalDate retNow = null;
        if ("次日".equals(type)) {
            retNow = initDate.plusDays(1);
        } else if ("下周一日".equals(type)) {
            retNow = initDate.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
        } else if ("本月十六日".equals(type)) {
            retNow = initDate.withDayOfMonth(16);
        } else if ("下月一日".equals(type)) {
            retNow = initDate.with(TemporalAdjusters.firstDayOfNextMonth());
        }
        return retNow;
    }

    /**
     * 取后几天的日期
     *
     * @param day
     * @return
     */
    public static String getNextDay(String day) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate date = LocalDate.parse(day, formatter);
        LocalDate nextDay = date.plusDays(1);
        String nextDayString = nextDay.format(formatter);
        return nextDayString;
    }

    /**
     * 时间戳转时间字符串
     *
     * @param timestamp
     * @return
     */
    public static String getDateByTimestamp(long timestamp) {
        Instant instant = Instant.ofEpochMilli(timestamp);
        String formattedDate = formatter.format(instant);
        return formattedDate;
    }

    public static int compareTimeSizes(String aDate, String bDate) {
        if (aDate.indexOf("T") != -1) {
            aDate = aDate.replace("T", " ");
        }

        if (bDate.indexOf("T") != -1) {
            bDate = bDate.replace("T", " ");
        }

        if (aDate.indexOf("00:00:00") == -1) {
            aDate += " 00:00:00";
        }

        if (bDate.indexOf("00:00:00") == -1) {
            bDate += " 00:00:00";
        }

        // 将字符串解析为LocalDateTime对象
        LocalDateTime dateTime1 = LocalDateTime.parse(aDate, formatter1);
        LocalDateTime dateTime2 = LocalDateTime.parse(bDate, formatter1);

        // 比较两个时间
        if (dateTime1.isBefore(dateTime2)) {
            // a 小于 b 返回 -1
            return -1;
        } else if (dateTime1.isAfter(dateTime2)) {
            // a 大于 b 返回 1
            return 1;
        } else {
            // a 等于 b 返回 0
            return 0;
        }
    }

    public static void main(String[] args) {
        String a = "2025-01-15 00:00:00";
        String b = "2025-01-15 00:00:00";
        System.out.println(compareTimeSizes(a, b));
    }
}
